<?php

require_once(dirname(dirname(dirname(__FILE__))).'/appconf.php');
  
require_once "CMS.class.php";

$local_config = array(
    'this_cgi'       => 'cms/builder/event.php',
    'tmpl'           => array('base_path' => 'cms/builder/event/'), # full path = $this->param('TMPL').$
    'database'       => '',
    'table'          => 'event',
    'cms_auth_group'  => 'Editorial Content',
    '#MESSAGE#'      => array(),
);

class cms_builder_event extends CMS{

  function setup(){
    $this->run_modes('list',
                     'edit',
                     
                     'update', 
                     'mupdate',
                     'view', 
                     
                     'add', 
                     'madd', 
                     'showadd', 'edit_after_add',
                     
                     'showdel', 
                     'del', 
                     
                     'showsearch','search','clearsearch',
                     
                     'showsetting', 'setting',
                     
                     'ajax_update_field',
                     
                     'trap'
                    );
    $this->start_mode('list');
    $this->set_path_info_position(array('id'=>1));
    parent::setup();
  }

  function cgiapp_prerun($rm=''){
    
    parent::cgiapp_prerun($rm); # login, targeted to run CMS_Login.class.php 
    
  }

  function cgiapp_postrun(&$body){
    parent::cgiapp_postrun($body);

    $a_js = array();
    if (method_exists($this, 'inject_js') && count($this->inject_js()) > 0){ // some old CMS.class.php don't support yet
    	$a_js = $this->inject_js();
    }
    
  //	
    
    $login = $this->get_cms_username();
    if (!empty_string($login)){
      array_push($a_js, "\$('#login').html('Hi $login!  <a href=\"/cms/builder/logout.php\" style=\"color:red;\">Logout</a>');");
    }
  
    if ($this->header_type() == 'redirect'){
      return;	
    }
    
    $a_msg = array();
    $a_current_msg = $this->message();
    $a_session_msg = $this->get_message_from_session();
    foreach ($a_session_msg as $msg){
    	array_push($a_msg, $msg);
    }
    foreach ($a_current_msg as $msg){
    	array_push($a_msg, $msg);
    }
    
    $message = '';
    if (count($a_msg)>0){
      $message = implode('<BR>', $a_msg);
      array_push($a_js, "\$(document).ready(function(){ $(\"#dialog-modal\").dialog({height: 140,modal: true});  });");
    }

    if (count($a_js) > 0){
      $temp = "<script>".implode('', $a_js)."</script>";
      if ($message != ''){
        $temp .= html_dialog('Notice', $message);
      }
      $body = preg_replace('/(<!--POSTRUNJS-->)/', $temp, $body, 1);
      
    }
    
  }

#no no login

  // some
  function trap(){
	  $a_msg = $this->message();
	  $message = '';
	  if (count($a_msg)>0){
	    $message = implode('<BR>', $a_msg);
	    $this->tmpl_assign('title', 'Application Error');
	    $this->tmpl_assign('body',  $message);
  	  return $this->load_tmpl($this->param('TMPL'),  'error.html');
    }
    return '';
  }

  function action_list(){
  	if (! $this->user_can('list') ) return $this->trap();
    
    # on_start_list() *removed* - give it a chance to modify FK and TOP

    $dbh_r = $this->db_connect('read');
    $list_control = $this->update_listing_ordering();
    $sqlstr = 'SELECT * FROM '.$this->param('table').
              $this->listing_condition();
    if ($this->get_q('page', false, 'int')===false) $this->q_param('page', $this->s_param('cms_builder_event#'.'page'));

    $event_type = $this->create_lookup_array($dbh_r, "event_type", 'id', "cname", ' where status=1'); 
    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", 'where id>0 and status=1'); 
    $h_feature = array(
      'event_type'       => array('h:label',         'event_type',      $event_type ,array()),
      'has_detail'       => array('ny:label',        'has_detail',      ),
      'member_type'      => array('h:label',         'member_type',     $member_type ,array()),
      'status'           => array('status:label',    'status',          ),
      
      '#MULTIPLE#' =>1,
      '#PAGESIZE#' => 20,
      '#PAGELIST#' => '1,2,3',
      '#PAGE#'     => $this->get_param('q', 'page', 1, 'int'),
      '#GET_SELECTED_ID#' => 1,
      
      );
    list($list_data, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);

    $this->s_param('cms_builder_event#'.'page', $this->get_q('page',1));

	  if (count($list_data) == 0){

	    //no data selected by previous process_select_result
	    if ($this->get_q('page') != 1 &&  $this->s_param('cms_builder_event#'.'page') > 1){
	      $this->q_param('page', 1);
	      return $this->action_list();
	    }

      $this->message('No data.');
	  }

    $this->tmpl_assign('user_permission', $this->get_user_permission());
    $this->tmpl_assign('list_control', $list_control);

    $a_search_cond = $this->s_param('cms_builder_event#'.'SEARCH_COND');
    $is_search = empty($a_search_cond)  ? 0: 1;

    $this->tmpl_assign('title_noun', $is_search > 0 ? 'Search Result of' : 'List of');
    $this->tmpl_assign('clear_search_link', $is_search > 0 ? html_link(' [Clear Search Result]', $this->self_url(array('action'=>'clearsearch'))) : '');
    $this->tmpl_assign('list_data', $list_data);
    $this->tmpl_assign('pagelist', $a_pagelist);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    
    return $this->load_action_tmpl('list');
  }

  function update_listing_ordering(){
  	$a_allowed_sorting_field = array();
  	if (count($a_allowed_sorting_field) == 0){
  		return array();
  	}
  	$sortbyfield = $this->s_param('cms_builder_event#'.'sortby');
    #echo $sortbyfield;
    $a_sortbyfield = explode(',', $sortbyfield);
    $h_sortbyfield = array();
    foreach ($a_sortbyfield as $fieldname_order){
    	$a_temp = explode(' ', $fieldname_order);
    	$field = $a_temp[0];
    	$order = isset($a_temp[1])?$a_temp[1]:'';
    	#echo 'F['.$field.'] or['.$fieldname_order.']';
      $h_sortbyfield[$field]= $order;
    }
    
    $list_control = array();
    $a_result = array();
    $count = 0;
  	foreach ($a_allowed_sorting_field as $field){
  	  $sort_order=$this->get_q('sort_'.$field, '');
  	  if ($sort_order == ''){
  	  	if (isset($h_sortbyfield[$field])){
  	    	#echo "{".$h_sortbyfield[$field].'}';
  	  	  $sort_order =  $h_sortbyfield[$field];
     	  } else {
     	  	$sort_order = 'none';
     	  }	
  	  }
  	  
  	  if ($sort_order == 'none' || $sort_order == ''){
        $list_control['sort_'.$field] = html_img('/cms/images/ico/up_down_arrow.gif', '?sort_'.$field.'=desc');
        #array_push ($a_result, $field.' none');
        #echo 'list_control none sort_ '.$field;
  	  } elseif ($sort_order == 'desc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/down_arrow.gif', '?sort_'.$field.'=asc');
  	  	array_push ($a_result, $field.' desc');
  	  	#echo 'list_control down sort_ '.$field;
  	  } elseif ($sort_order == 'asc'){
  	  	$list_control['sort_'.$field] = html_img('/cms/images/ico/up_arrow.gif', '?sort_'.$field.'=none');
     	  array_push ($a_result, $field.' asc');
     	  #echo 'list_control up sort_ '.$field;
      }
  	  
  	}
  	
  	$temp = implode(',',$a_result);
  	#echo $temp.']';
  	$this->s_param('cms_builder_event#'.'sortby', $temp);
  	return $list_control;
  }

  function listing_condition(){
    $a_where = array();

    $session_show_all_status = $this->s_param('cms_builder_event#'.'SETTING_SHOWALLSTATUS');
    switch($session_show_all_status){
      case 'status_all':
        break;
      case 'status_0':
        array_push($a_where, "status=0", "and");
        break;
      case 'status_2':
        array_push($a_where, "status=2", "and");
        break;
      case 'status_none': # no status field
        break;
      default:
        array_push($a_where, "status>=1", "and");
        break;
    }	

    $a_search_condition = $this->s_param('cms_builder_event#'.'SEARCH_COND');
    if (is_array($a_search_condition) && !empty($a_search_condition)){
      $a_where = array_merge($a_where, $a_search_condition);
    }

#    #array_push($a_where, "");#
#
#    $a_order = array();
#    $sortbyfield = $this->get_param('s','sortby', 'id');
#    $sortorder   = $this->get_param('s','sortorder', '');#
#
#    $a_sortbyfield = explode(',', $sortbyfield);
#    $a_sortorder   = explode(',', $sortorder);
#
#    foreach ($a_sortbyfield as $sortbyfield){
#      $sortorder = array_shift($a_sortorder);
#
#      array_push($a_order, "$sortbyfield $sortorder");
#   }

    $sortby = $this->s_param('cms_builder_event#'.'sortby');
    if ($sortby == ''){
    	$sortby = ' id desc';
    }

    $final_str = '';
    if (count($a_where) > 0){
      array_pop($a_where);
      $final_str = ' where '.implode(' ', $a_where);
    }
    #if (count($a_order) > 0){
    #  $final_str .= ' order by '.implode(' and ', $a_order);
    #}
    $final_str .= ' order by '.$sortby;
    
    return $final_str;
  }

  function action_edit($id=null){
    if (! $this->user_can('edit') ) return $this->trap();
    if ($id === null){
       $id = $this->get_param('pq','id',  0, 'int');
    }
    
    if ($id == 0
      
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $event_type = $this->create_lookup_array($dbh_r, "event_type", 'id', "cname", ' where status=1'); 
    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", 'where id>0 and status=1'); 
    $cms_user = $this->create_lookup_array($dbh_r, "cms_user", 'id', "name", 'where status=1'); 
    $h_feature = array(
      
      'title'            => array('f:func',          'title',           'html_fix_edit_text'),
      'event_type'       => array('h:list',          'event_type',      $event_type ,array()),
      'event_time'       => array('f:func',          'event_time',      'html_fix_edit_text'),
      'place'            => array('f:func',          'place',           'html_fix_edit_text'),
      'event_url'        => array('f:func',          'event_url',       'html_fix_edit_text'),
      'intro'            => array('f:func',          'intro',           'html_fix_edit_textarea'),
      'has_detail'       => array('ny:list',         'has_detail',      ),
      'body'             => array('f:func',          'body',            'html_fix_edit_textarea'),
      'product'          => array('f:func',          'product',         'html_fix_edit_text'),
      'brand_str'        => array('f:func',          'brand_str',       'html_fix_edit_text'),
      'member_type'      => array('h:radio',         'member_type',     $member_type ,array()),
      'points'           => array('f:func',          'points',          'html_fix_edit_text'),
      'click'            => array('f:func',          'click',           'html_fix_edit_text'),
      'likes'            => array('f:func',          'likes',           'html_fix_edit_text'),
      'quota'            => array('f:func',          'quota',           'html_fix_edit_text'),
      'apply_num'        => array('f:func',          'apply_num',       'html_fix_edit_text'),
      'video'            => array('f:func',          'video',           'html_fix_edit_text'),
      'video_details'    => array('f:func',          'video_details',   'html_fix_edit_textarea'),
      'terms'            => array('f:func',          'terms',           'html_fix_edit_textarea'),
      'addedby'          => array('h:label',         'addedby',         $cms_user ,array()),
      'modifiedby'       => array('h:label',         'modifiedby',      $cms_user ,array()),
      'approvedby'       => array('h:label',         'approvedby',      $cms_user ,array()),
      'status'           => array('status:radio',    'status',          ),
                       );
    
    if ( $this->user_can('approve', 1) ){
    	$h_feature['status'] = array('status:radio',    'status',          );
    } else {
    	$h_feature['status'] = array('status:label',    '',          );
    }	

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    
    $this->audit_log('edit', $id);
    
    $this->tmpl_assign('edit_data', $h_row[0]);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('edit');
  }

  function action_view(){
    if (! $this->user_can('view') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    if ($id == 0
      
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');

    $dbh_r = $this->db_connect('read');

    $sqlstr = 'SELECT * FROM '.$this->param('table')." where id=".$id;
    
    $event_type = $this->create_lookup_array($dbh_r, "event_type", 'id', "cname", ' where status=1'); 
    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", 'where id>0 and status=1'); 
    $cms_user = $this->create_lookup_array($dbh_r, "cms_user", 'id', "name", 'where status=1'); 
    $h_feature = array(
      
      'event_type'       => array('h:label',         'event_type',      $event_type ,array()),
      'has_detail'       => array('ny:label',        'has_detail',      ),
      'member_type'      => array('h:label',         'member_type',     $member_type ,array()),
      'addedby'          => array('h:label',         'addedby',         $cms_user ,array()),
      'modifiedby'       => array('h:label',         'modifiedby',      $cms_user ,array()),
      'approvedby'       => array('h:label',         'approvedby',      $cms_user ,array()),
      'status'           => array('status:label',    'status',          ),
                        );

    list($h_row, $a_pagelist, $a_processed_id) = $this->process_select_result($dbh_r, $sqlstr, $h_feature);
    $this->audit_log('view', $id);
    
    $this->tmpl_assign('view_data', $h_row[0]);
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('view');
  }

  function action_update(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    if ($id === false
      
      ) throw new CgiappErrorException(100, __METHOD__.' Invalid Parameter!');
    
    $dbh_w    = $this->db_connect('write');
    $original_status = db_select_one($dbh_w, 'select status from '.$this->param('table').' where id=?', $id);

    $h_feature = array(

		'cover'              => 'skip',             

		'cover2'             => 'skip',             

    );
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);
    $upload_changed = 0;
    $upload_changed += $this->upload_cover_impl($id, $this->get_q('cover_http', 'cover'), 
          array('clear' => $this->get_q('cover_clear', '0', 's:int')
          ));

$upload_changed += $this->upload_cover2_impl($id, $this->get_q('cover2_http', 'cover2'), 
          array('clear' => $this->get_q('cover2_clear', '0', 's:int')
          ));

    if ($changed > 0 || $upload_changed > 0){
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id=?", array($this->get_cms_userid(),$id)); 
      
      $this->audit_log('update', $id);
    }
    
    if ($this->get_q('subaction') == 'edit_after_update'){
      return $this->action_edit($id);
    }
    return  $this->cms_redirect_default_action( array() );
  }

  function action_mupdate(){
    if (! $this->user_can('edit') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    
    $h_feature = array(
    
    );
    
    //$this->mupdate_modify_feature(\%feature) if ($this->can('mupdate_modify_feature'));

    $a_changed = $this->update_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    $a_id = $this->q_param('id');
    foreach ($a_id as $id){
      $upload_changed = 0;
      
      if ($upload_changed > 0 && !in_array($id, $a_changed)){    
         array_push($a_changed, $id);
       } 

    }

    if (count($a_changed)>0){
      $changed = implode(',' , $a_changed);
      db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id in ($changed)", array($this->get_cms_userid()));       
      $this->audit_log('update', $changed);
    }

    return $this->cms_redirect_default_action(array());
  }
    
  function action_showadd(){
    if (! $this->user_can('add') ) return $this->trap();
    
    $dbh_r = $this->db_connect('read');

    $event_type = $this->create_lookup_array($dbh_r, "event_type", 'id', "cname", ' where status=1'); 
    $member_type = $this->create_lookup_array($dbh_r, "member_type", 'id', "cname", 'where id>0 and status=1'); 
    $h_feature = array(
      
      'event_type'       => array('h:list',          'event_type',      $event_type ,array()),
      'has_detail'       => array('ny:list',         'has_detail',      ),
      'member_type'      => array('h:radio',         'member_type',     $member_type ,array()),
      'status'           => array('status:radio',    'status',          ),
      );
    $h_default_value = array(
      'title' => '',
      'starttime' => '',
      'endtime' => '',
      'event_type' => '',
      'event_date' => '',
      'event_time' => '',
      'place' => '',
      'event_url' => '',
      'intro' => '',
      'has_detail' => '0',
      'body' => '',
      'product' => '',
      'brand_str' => '',
      'member_type' => '',
      'points' => '',
      'click' => '',
      'likes' => '',
      'quota' => '',
      'apply_num' => '',
      'video' => '',
      'video_details' => '',
      'terms' => '',
      'status' => '1',
      );
                 
    $showadd_data = $this->process_showadd_feature($dbh_r, $h_feature, $h_default_value);

    $this->tmpl_assign('showadd_data', $showadd_data);
    
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showadd');
  }

  function action_add(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w    = $this->db_connect('write'); # db_connect default is readonly

    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 

    );
    $changed = $this->add_to_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0 ){
      $id = db_last_insert_id($dbh_w);
      db_do($dbh_w, "update ".$this->param('table')." set addtime=NOW(),lastmodify=NOW(),addedby=?,modifiedby=? where id=?", array($this->get_cms_userid(),$this->get_cms_userid(),$id)); 
      
    }
    $upload_changed = 0;
     
    $this->audit_log('add', $id);

  if ($this->get_q('subaction') == 'edit_after_add'){
    return $this->action_edit($id);
  }
  
  if ($this->get_q('subaction') == 'showadd_after_add'){
	  return $this->action_showadd();
	}
  
    return $this->cms_redirect_default_action(array());
  }

  function action_madd(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w       = $this->db_connect('write');
    $h_feature = array(
    'addtime'=>'skip','lastmodify'=>'skip', 
    #'addtime' => 'addtime', 'lastmodify' => 'lastmodify',
    
    );
    $changed   = $this->add_to_table_multiple_row($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if (count($a_changed) > 0){
      foreach ($a_changed as $id){
        $row_affected = $dbh_w->exec("update ".$this->param('table')." set lastmodify = NOW() where id = '$id'") ;
      }
    }
    
		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('madd', $changed_id);
	  }
	
    return $this->cms_redirect_default_action(array());
  }

  /*
   *
   */
  function action_del(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(

    '#DELETE_MODE#' => 'hidden'
   );
    $this->delete_from_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_param);
    
    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id=?", array($this->get_cms_userid(),$id)); 
    $this->audit_log('del', 'hidden-'.$id);
    
    return $this->cms_redirect_default_action(array());
  }

  function action_mdel(){
    if (! $this->user_can('del') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    # input check
    $a_selected   = array();
    $a_keys      = $this->get_q('mselected_id'); // we may support this field as configurable so that not only cms can use
    if (is_array($a_keys) ){
	    foreach ($a_keys as $row_key){    	
	    	if (ctype_digit($row_key)){
	        array_push($a_selected, $row_key);
	      }
	    }
    }
    if (count($a_selected) == 0){
    	$this->message('Please select the ID for records to be deleted!');
      return $this->cms_redirect_default_action(array());    	
    }
    # end input check
    
    $dbh_w  = $this->db_connect('write');
    $h_param = array(
      
      '#DELETE_MODE#' => 'hidden'
      );
    $a_changed = $this->delete_multiple_from_table($dbh_w, $this->param('table'),'HTTP_POST', $h_param);
    
 		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    db_do($dbh_w, "update ".$this->param('table')." set lastmodify=NOW(),modifiedby=? where id in ($changed_id)", array($this->get_cms_userid())); 
	  }

		if (count($a_changed) > 0){
		  $changed_id = implode(',', $a_changed);
	    $this->audit_log('mdel', 'hidden-'.$changed_id);
	  }
	
    return $this->cms_redirect_default_action(array());
  }

  function action_help(){
  	#if (! $this->user_can('help') ) return $this->trap();
    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
  	return $this->load_action_tmpl('help');
  }
/**HELP:__HELP**/

  function action_showsearch(){
    if (! $this->user_can('list') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_r = $this->db_connect('read');
    $h_default_value = array(
      'title'=>'',# add session support later
      'starttime'=>'',# add session support later
      'endtime'=>'',# add session support later
      'event_type'=>'',# add session support later
      'event_date'=>'',# add session support later
      'event_time'=>'',# add session support later
      'place'=>'',# add session support later
      'event_url'=>'',# add session support later
      'intro'=>'',# add session support later
      'has_detail'=>'0',# add session support later
      'body'=>'',# add session support later
      'product'=>'',# add session support later
      'brand_str'=>'',# add session support later
      'member_type'=>'',# add session support later
      'points'=>'',# add session support later
      'click'=>'',# add session support later
      'likes'=>'',# add session support later
      'quota'=>'',# add session support later
      'apply_num'=>'',# add session support later
      'video'=>'',# add session support later
      'video_details'=>'',# add session support later
      'terms'=>'',# add session support later
      'status'=>'1',# add session support later
      );

    $h_feature = array(
      'title' => '',
                 );

    $showsearch_data = $this->process_showsearch_feature($dbh_r, $h_feature, $h_default_value);
    $this->tmpl_assign('showsearch_data', $showsearch_data);

    if (method_exists($this, 'get_navigation')){$this->tmpl_assign('navigation', $this->get_navigation(4));}
    return $this->load_action_tmpl('showsearch');
  }

  function clearsearch(){
  	
    $this->search_clear('cms_builder_event#');
    return $this->cms_redirect_default_action(array());
  }

  function action_search(){
    if (! $this->user_can('list') ) return $this->trap();
    #<!--START:__PSAUTH-->return $this->psauth_no_access() if (not $this->psauth_can_access('search'));<!--END:__PSAUTH-->

    $h_feature = array(
      
      );
    list ($flag, $a_condition) = $this->search_build_sql($h_feature);
    if ($flag == 1){
      return $this->errmsg('no_search_input', 2) ;
    }

    if (is_array($a_condition)  && !empty($a_condition)){
      $this->s_param('cms_builder_event#'.'SEARCH_COND', $a_condition);
    }

    return $this->cms_redirect_default_action(array());
  }

/**START:COPY**/

##COPY_TYPE_FUNC##
  function action_copy(){
    if (! $this->user_can('add') ) return $this->trap();
    $id = $this->get_param('pq','id',  0, 'int');
    
    $dbh_w = $this->db_connect('write');

    $h_param = array(
    
                   );

    list($count, $new_id)=  $this->copy_row_by_key($dbh_w, $this->param('table'), 'id', $id, $h_param);
    #my ($count, $new_id) = $this->copy_row_by_key($dbh, $this->param('table'), 'id', $id, '', %feature);
    /**START:COPY_BY_FK_HAS_CHILD**/
    if ($this->q_param('subaction') == 'with_child'){
      #$this->##PS_SHARE_CHILD_MODULE_PREFIX##copy_by_parent_key($id, $new_id);
    }
    /**END:COPY_BY_FK_HAS_CHILD**/

    return  $this->action_edit($new_id);
  }

/**END:COPY**/

// Supplementary function add here
 /* $source: 1/ fieldname in form 
  *          2. url copy
  *          3. local path  
  *  if prefer http copy
  *    $this->upload_file_impl($id, $this->get_q('file_http', 'file'); 
  *  or just upload
  *    $this->upload_file_impl($id, 'file');
  * return 1: changed, 0 not chanaged
  */
function upload_cover_impl($id, $source, $h_param){  
  require_once 'ImageUpload.php';
  require_once 'UploadPath.php'; # group to FileUpload later

  if ($h_param['clear']){
  	$fieldname = 'cover';
  	$h_param = array( 
  	                  $fieldname.'_image1'=>'',$fieldname.'_imagesize1'=>'',$fieldname.'_imageparam1'=>'',
  	                  $fieldname.'_image2'=>'',$fieldname.'_imagesize2'=>'',$fieldname.'_imageparam1'=>'',
  	                  
  	                  'id'=>$id);
  	$this->update_table($this->db_connect('write'), $this->param('table'), $h_param);
  	return 1; # changed
  }
    
  $upload = new ImageUpload($source, 'jpg,gif,jpeg,png' , 52428800);
  
  $relative_output_path = 'upload/event/cover/'; # relative for show in web, be still, it can be absolute path
  $absolute_output_path = $this->param('WWW').'upload/event/cover/';  # base path for save to file system
  
  $h_setting = array(
	 1=>array( 'convert_to'=>'jpg,png','max_dim' => '159x109','mode'=>1,'filename'=>get_upolad_image_path($id,1,array( 'path_by_date'=>8 , 'path_by_id'=>2,'default_filename'=>'', 'append_updatetime'=>'2' )) ),
	
   2=>array( 'convert_to'=>'jpg,png','max_dim' => '320x320','mode'=>1,'filename'=>get_upolad_image_path($id,2,array( 'path_by_date'=>8 , 'path_by_id'=>2,'default_filename'=>'', 'append_updatetime'=>'2' )) ),	

                    );
  
  list($flag, $a_processed_image) = $upload->save($absolute_output_path, $h_setting);
  if ($flag != 0){
    if ($flag != 10) $this->message("Failed to upload [$source]. Error: ".$flag);
    //return 0; # not chagned
    return 0;
  }
  //error_log("Upload_file_impl: Flag: $flag - $message");  
  
  foreach ($a_processed_image as $img){
    list($image_sequence, $image_size, $relative_path, $image_param) = $img;
    $fieldname = 'cover';
    $dbh_w = $this->db_connect('write');
	  if ($image_sequence == 0){
	  	 db_do($dbh_w, "update ".$this->param('table')." set {$fieldname}_image{$image_sequence}=?, {$fieldname}_imagesize{$image_sequence}=? where id=?", array($relative_output_path.$relative_path, $image_size, $id));
	  } else {
	  	db_do($dbh_w, "update ".$this->param('table')." set {$fieldname}_image{$image_sequence}=?, {$fieldname}_imagesize{$image_sequence}=?, {$fieldname}_imageparam{$image_sequence}=? where id=?", array($relative_output_path.$relative_path, $image_size, $image_param, $id));
	  }
	
  }
  return 1;
} 

 /* $source: 1/ fieldname in form 
  *          2. url copy
  *          3. local path  
  *  if prefer http copy
  *    $this->upload_file_impl($id, $this->get_q('file_http', 'file'); 
  *  or just upload
  *    $this->upload_file_impl($id, 'file');
  * return 1: changed, 0 not chanaged
  */
function upload_cover2_impl($id, $source, $h_param){  
  require_once 'ImageUpload.php';
  require_once 'UploadPath.php'; # group to FileUpload later

  if ($h_param['clear']){
  	$fieldname = 'cover2';
  	$h_param = array( 
  	                  $fieldname.'_image1'=>'',$fieldname.'_imagesize1'=>'',$fieldname.'_imageparam1'=>'',
  	                  $fieldname.'_image2'=>'',$fieldname.'_imagesize2'=>'',$fieldname.'_imageparam1'=>'',
  	                  
  	                  'id'=>$id);
  	$this->update_table($this->db_connect('write'), $this->param('table'), $h_param);
  	return 1; # changed
  }
    
  $upload = new ImageUpload($source, 'jpg,gif,jpeg,png' , 52428800);
  
  $relative_output_path = 'upload/event/cover2/'; # relative for show in web, be still, it can be absolute path
  $absolute_output_path = $this->param('WWW').'upload/event/cover2/';  # base path for save to file system
  
  $h_setting = array(
	 1=>array( 'convert_to'=>'jpg,png','max_dim' => '159x109','mode'=>1,'filename'=>get_upolad_image_path($id,1,array( 'path_by_date'=>8 , 'path_by_id'=>2,'default_filename'=>'', 'append_updatetime'=>'2' )) ),
	
   2=>array( 'convert_to'=>'jpg,png','max_dim' => '320x320','mode'=>1,'filename'=>get_upolad_image_path($id,2,array( 'path_by_date'=>8 , 'path_by_id'=>2,'default_filename'=>'', 'append_updatetime'=>'2' )) ),	

                    );
  
  list($flag, $a_processed_image) = $upload->save($absolute_output_path, $h_setting);
  if ($flag != 0){
    if ($flag != 10) $this->message("Failed to upload [$source]. Error: ".$flag);
    //return 0; # not chagned
    return 0;
  }
  //error_log("Upload_file_impl: Flag: $flag - $message");  
  
  foreach ($a_processed_image as $img){
    list($image_sequence, $image_size, $relative_path, $image_param) = $img;
    $fieldname = 'cover2';
    $dbh_w = $this->db_connect('write');
	  if ($image_sequence == 0){
	  	 db_do($dbh_w, "update ".$this->param('table')." set {$fieldname}_image{$image_sequence}=?, {$fieldname}_imagesize{$image_sequence}=? where id=?", array($relative_output_path.$relative_path, $image_size, $id));
	  } else {
	  	db_do($dbh_w, "update ".$this->param('table')." set {$fieldname}_image{$image_sequence}=?, {$fieldname}_imagesize{$image_sequence}=?, {$fieldname}_imageparam{$image_sequence}=? where id=?", array($relative_output_path.$relative_path, $image_size, $image_param, $id));
	  }
	
  }
  return 1;
} 

  // ajas update a field
  function ajax_update_field(){
    $id   = $this->get_q('id', 0, 'int');
    if ($id == 0) return 'invalid ID';

    ################################################
    # General update, common for all
    ################################################

    $dbh_w    = $this->db_connect('write');
    $h_feature = array();
    $changed = $this->update_table($dbh_w, $this->param('table'), 'HTTP_POST', $h_feature);

    if ($changed > 0){
      $row_affected = db_do($dbh_w, "update ".$this->param('table')." set lastmodify = NOW() where id =?", array($id)) ;
    }

    $dbh_r    = $this->db_connect('read');
    $field  = $this->q_param('#FIELD#');
    list ($value) = db_selectrow_array($dbh_r, "select $field from ".$this->param('table')." where id=?", array($id));
//    ### custom, change by type table
//    if ($field == 'aseip'){
//      list ($value) = db_selectrow_array($dbh, "select cname from test.dummy_type where id=?", array($value));
//    return $value;
//    }
//    #####

    return $value;

  }

/* Custom Class Function Implementation start here */

}//end class

$webapp = new cms_builder_event(
   array('PARAMS' => array_merge($site_global_config, $local_config))
         );
$webapp->run();

/* Custom Helper Function Implementation start here */

?>
